import { createRouter, createWebHistory } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'
import { useTabsStore } from '@/stores/tabs'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home' // 设置为主页为默认页面
    },
    {
      path: '/index',
      redirect: '/index/login',
      component: () => import('@/views/Index.vue'),
      children: [
        {
          path: 'login',
          name: 'login',
          component: () => import('@/views/Login.vue')
        },
        {
          path: 'registry',
          name: 'registry',
          component: () => import('@/views/Registry.vue')
        },
      ]
    },
    {
      path: '/home',
      name: 'home',
      redirect: '/home/default',
      component: () => import('@/views/Home.vue'),
      children: [
        {
          path: 'default',
          component: () => import('@/components/Index.vue')
        },
        {
          path: 'books',
          component: () => import('@/components/case/Books.vue')
        },
        {
          path: 'files',
          component: () => import('@/components/case/Files.vue')
        },
        {
          path: 'weathers',
          component: () => import('@/components/case/Weathers.vue')
        },
        {
          path: 'users',
          component: () => import('@/components/system/Users.vue')
        },
        {
          path: 'roles',
          component: () => import('@/components/system/Roles.vue')
        },
        {
          path: 'menus',
          component: () => import('@/components/system/Menus.vue')
        },
        {
          path: 'settings',
          component: () => import('@/components/Settings.vue')
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue')
    }
  ]
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 登录和注册页面，需要在未登录状态下访问，否则将重定向到主页
  if (to.path.startsWith('/index')) {
    if (sessionStorage.getItem('token')) {
      return next('/home');
    } else {
      return next();
    }
  }

  let permissionStore; 
  let tabsStore;

  // 即使没有配置路由，导航守卫仍能监听到路由地址
  // 主页，需要在已登录状态下访问，否则将重定向到登录页
  if (to.path.startsWith('/home')) {
    if (sessionStorage.getItem('token')) {
      // 将使用pinia的步骤放到导航守卫中(即：vue初始化时不做pinia操作，需要延迟调用)
      // Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. 
      // Are you trying to use a store before calling "app.use(pinia)"?
      if(!permissionStore) {
        permissionStore = usePermissionStore()
      } 
      if(!tabsStore) {
        tabsStore = useTabsStore()
      }
      // 判断目的path是否在pathList可访问地址中
      const path = to.path
      if(permissionStore.pathList.find(item => item === path)) {
        // 修改当前选中菜单
        tabsStore.currentPath = path
        // 新增/选中tab
        addOrSelectTab(path, permissionStore, tabsStore)
        return next();
      } else{
        return next('/notfound')
      }
    } else {
      return next('/index');
    }
  }
  next();
});

/**
 * 新增或选中新的tab
 * @param {*} path 将要跳转的path
 * @param {*} permissionStore permission存储对象
 * @param {*} tabsStore tabs存储对象
 */
const addOrSelectTab = (path, permissionStore, tabsStore) => {
  // 1.判断Tabs中是否已存在
  let tab = tabsStore.tabs.find(item => item.path === path)
  if (!tab) {
      // 2.如果不存在,去routerList中查找tab
      tab = permissionStore.routerList.find(item => item.path === path)
      // 3.添加到tabs
      tabsStore.tabs.push(tab)
  }
  // 4.选中tab
  tabsStore.selectTab = tab.name
}

export default router